package com.zjuee.gateway.utils;

import com.alibaba.fastjson.JSONObject;
import com.zjuee.core.utils.IpUtils;
import org.apache.catalina.connector.ClientAbortException;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author wu liang
 * @since 2020/8/13 9:54
 */
public class HttpResponseUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpResponseUtils.class);


    public static void sendJsonMessage(ServletResponse response, Object msg) {
        if (response==null) {
            return;
        }
        String jsonMsg = "";
        if (msg != null) {
            jsonMsg = JSONObject.toJSONString(msg);
        }
        HttpResponseUtils.sendJsonMessage(response, jsonMsg);
    }



    public static void sendJsonMessage(ServletResponse response, String jsonMsg) {
        if (response==null) {
            return;
        }
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        try {
            httpResponse.reset();
        } catch (Exception e) {
            logger.warn("httpResponse 已经关闭，无法再次打开");
            return;
        }
        // 允许跨域相关设置
        // httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        // httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setCharacterEncoding("UTF-8");

        // 禁用浏览器缓存
        httpResponse.setHeader("Cache-Control","no-store");
        httpResponse.setHeader("Pragrma","no-cache");
        httpResponse.setDateHeader("Expires",0);
        httpResponse.setStatus(HttpStatus.OK.value());

        try {
            PrintWriter out = httpResponse.getWriter();
            out.println(jsonMsg);
            out.flush();
        } catch (ClientAbortException e) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String ip = IpUtils.getIpAddr(request);
            logger.error(ip + "\t客户端已断开连接：" + e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }

    }
}
